package cn.gp.chatclient.websocket;

import cn.gp.chatclient.config.ClientConfig;
import cn.gp.chatclient.model.MessageVo;
import cn.gp.chatclient.model.ResponseVo;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import javax.swing.*;
import java.net.URI;
import java.util.function.Consumer;
import java.util.concurrent.CompletableFuture;
import java.io.IOException;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

@Slf4j
public class ChatWebSocketClient extends WebSocketClient {
    private static ChatWebSocketClient instance;
    private Consumer<String> messageHandler;
    private final Long userId;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();

    public ChatWebSocketClient(String serverUrl) {
        super(URI.create(serverUrl));
        this.userId = null;
    }

    public static synchronized void initialize(String serverUrl, Long userId) {
        if (instance == null) {
            try {
                instance = new ChatWebSocketClient(serverUrl);
                instance.connect();
            } catch (Exception e) {
                throw new RuntimeException("WebSocket初始化失败", e);
            }
        }
    }

    public static ChatWebSocketClient getInstance() {
        if (instance == null) {
            throw new IllegalStateException("WebSocket未初始化");
        }
        return instance;
    }

    public void setMessageHandler(Consumer<String> handler) {
        this.messageHandler = handler;
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        log.info("WebSocket连接已建立");
    }

    @Override
    public void onMessage(String message) {
        log.info("收到消息: {}", message);
        if (messageHandler != null) {
            SwingUtilities.invokeLater(() -> messageHandler.accept(message));
        }
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        log.info("WebSocket连接已关闭: code={}, reason={}, remote={}", code, reason, remote);
    }

    @Override
    public void onError(Exception ex) {
        log.error("WebSocket错误", ex);
    }

    public Long getUserId() {
        return userId;
    }

    public CompletableFuture<ResponseVo<List<MessageVo>>> loadChatHistory(Long userId, Long contactId) {
        CompletableFuture<ResponseVo<List<MessageVo>>> future = new CompletableFuture<>();
        
        // 构建请求URL，添加limit参数
        String url = String.format("%s?userId=%d&contactId=%d&limit=50",
            ClientConfig.CHAT_HISTORY_BASE_URL, userId, contactId);
        
        log.info("请求聊天历史: url={}, userId={}, contactId={}", url, userId, contactId);
        
        Request request = new Request.Builder()
            .url(url)
            .get()
            .build();
            
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("获取聊天历史失败", e);
                future.completeExceptionally(e);
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    String errorMsg = "获取聊天历史失败: " + response;
                    log.error(errorMsg);
                    future.completeExceptionally(new IOException(errorMsg));
                    return;
                }
                
                try {
                    String responseBody = response.body().string();
                    log.info("收到聊天历史响应: {}", responseBody);
                    
                    // 服务器返回的是ApiResponse，客户端使用ResponseVo接收
                    ResponseVo<List<MessageVo>> responseVo = objectMapper.readValue(
                        responseBody,
                        new TypeReference<ResponseVo<List<MessageVo>>>() {}
                    );
                    
                    if (responseVo.isSuccess()) {
                        List<MessageVo> messages = responseVo.getData();
                        log.info("成功获取聊天历史，消息数量: {}", messages != null ? messages.size() : 0);
                    } else {
                        log.error("获取聊天历史失败: {}", responseVo.getMessage());
                    }
                    
                    future.complete(responseVo);
                } catch (Exception e) {
                    log.error("解析聊天历史响应失败", e);
                    future.completeExceptionally(e);
                }
            }
        });
        
        return future;
    }
}